import 'package:flustars/flustars.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:multi_dropdown/multi_dropdown.dart';
import 'package:yuan_hang_app/base/full_base_page.dart';
import 'package:yuan_hang_app/http/http_utils.dart';
import 'package:yuan_hang_app/res/w_constant.dart';
import 'package:yuan_hang_app/res/w_dimens.dart';
import 'package:yuan_hang_app/utils/common_utils.dart';
import 'package:yuan_hang_app/utils/size_utils.dart';
import 'package:yuan_hang_app/utils/common_req_utils.dart';
import 'package:yuan_hang_app/views/home/model/customer_tag.dart';
import 'package:yuan_hang_app/views/home/model/leads.dart';
import 'package:yuan_hang_app/views/home/view/leads/leads_assistance_page.dart';
import 'package:yuan_hang_app/views/home/view/leads/widget/common_date.dart';
import 'package:yuan_hang_app/widget/common_attachment.dart';
import 'package:yuan_hang_app/widget/w_line.dart';
import 'package:yuan_hang_app/widget/w_text.dart';
import 'package:yuan_hang_app/widget/w_toast.dart';

import '../../../../base/base_state.dart';
import '../../../../http/api.dart';
import '../../../../res/w_colors.dart';
import '../../../../utils/router_helper.dart';
import '../../../../widget/common_dialog.dart';
import '../../../../widget/label_item.dart';

class LeadsRecordPage extends StatefulWidget {
  const LeadsRecordPage({super.key});

  @override
  BaseState<LeadsRecordPage> createState() => _LeadsRecordPageState();
}

class _LeadsRecordPageState extends BaseState<LeadsRecordPage> {
  GlobalKey<LabelItemState>? isSubstitutionKey2;
  GlobalKey<LabelItemState>? isLoanKey2;
  GlobalKey<LabelItemState>? budgetKey2;
  GlobalKey<LabelItemState>? remarkKey2;
  GlobalKey<CommonAttachmentState>? picKey2;

  Leads leadsInfo = Leads();

  Map<String, dynamic> cityData = {"provincesData": {}, "citiesData": {}};

  List<Map> activityList = [];
  List<DropdownItem<CustomerTag>> items = [];
  final _controller = MultiSelectController<CustomerTag>();

  ///是否为销售顾问
  bool isSalesman = WConstant().userInfo.roleCode == "XSGW";


  List<Map> _attachmentImages = [];

  final ScrollController _listController = ScrollController();

  @override
  void initState() {
    super.initState();
    isSubstitutionKey2 = GlobalKey(debugLabel: "isSubstitutionKey2");
    isLoanKey2 = GlobalKey(debugLabel: "isLoanKey2");
    budgetKey2 = GlobalKey(debugLabel: "budgetKey2");
    remarkKey2 = GlobalKey(debugLabel: "remarkKey2");
    picKey2 = GlobalKey(debugLabel: "picKey2");


    _listController.addListener(() {
      if (_listController.position.pixels >=
          _listController.position.maxScrollExtent) {

        isSubstitutionKey2!.currentState?.refreshList(
            WConstant.yesOrNoList, leadsInfo.isSubstitution.toString());
        isLoanKey2!.currentState
            ?.refreshList(WConstant.yesOrNoList, leadsInfo.isLoan.toString());
        budgetKey2!.currentState
            ?.refreshInput(leadsInfo.budgetAmount ?? "");
        remarkKey2!.currentState?.refreshInput(leadsInfo.remark ?? "");
        picKey2!.currentState
            ?.refreshImageList(_attachmentImages);
      }
    });
    fetchCustomerTagList();
    fetchActivityList();
    getCityList();
    if (isSalesman) {
      leadsInfo.saleman = WConstant().userInfo.userId;
      leadsInfo.salemanName = WConstant().userInfo.employeeName;
    }
    leadsInfo.shopId = WConstant().userInfo.shopId;
  }

  fetchCustomerTagList() {
    CommonReqUtils.getTagList().then((list) {
      setState(() {
        items = (list ?? [])
            .map((item) => DropdownItem(label: item["tagName"], value: CustomerTag(id:int.parse(item["id"]), tagName:item["tagName"])))
            .toList();
        _controller.setItems(items);
      });
    });
  }

  void getCityList() {
    HttpUtils().get(Api.getRegionList2).then((value) {
      if (value.resultCode == 200) {
        cityData = value.data;
        setState(() {});
      }
    });
  }

  fetchActivityList() {
    showLoading();
    HttpUtils().get(Api.getActivityList).then((value) {
      hideLoading();
      if (value.resultCode == 200) {
        List data = value.data;
        if (data.isNotEmpty) {
          for (int i = 0; i < data.length; i++) {
            Map item = {
              "label": data[i]["activityName"],
              "value": data[i]["id"].toString()
            };
            activityList.add(item);
          }
        }
      } else {
        Toast.toast(value.errMsg);
      }
    });
  }

  saveClue() {
    if (Leads.check(leadsInfo)) {
      showLoading();
      HttpUtils().post(Api.addClue, data: leadsInfo.toVoJson()).then((value) {
        hideLoading();
        if (value.resultCode == 200) {
          int result = value.data["result"];
          if (result == 1) {
            CommonDialog.showConformDialog(
                context: context,
                title: "提示",
                content: value.data["tips"],
                cancelHide: true,
                onConfirm: (text) {
                  RouteHelper.maybePop(context);
                });
          } else if (result == 2) {
            CommonDialog.showConformDialog(
                context: context,
                title: "提示",
                content: value.data["tips"],
                onConfirm: (text) {
                  RouteHelper.pushWidget(
                      context,
                      LeadsAssistancePage(
                        leadsData: value.data,
                      ));
                });
          } else {
            Toast.toast("${value.data["tips"]}");
            RouteHelper.maybePop(context);
          }
        } else {
          Toast.toast(value.errMsg);
          RouteHelper.maybePop(context);
        }
      });
    }
  }

  @override
  FullBasePage buildState(BuildContext context) {
    return FullBasePage(
        title: "线索登记",
        resizeToBottomInset: true,
        child: Column(
          children: [
            Expanded(
                child: ListView(
              controller: _listController,
              padding: EdgeInsets.zero,
              shrinkWrap: true,
              children: [
                _cardItem("客户信息", _customerInfo(leadsInfo)),
                _cardItem("其他信息", _otherInfo(leadsInfo)),
              ],
            )),
            GestureDetector(
              onTap: () {
                CommonUtils.throttle(saveClue);
              },
              child: Container(
                margin: EdgeInsets.only(
                    top: 16.px, left: 24.px, right: 24.px, bottom: 16.px),
                width: SizeUtils.screenW() - 48.px,
                alignment: Alignment.center,
                height: 48.px,
                decoration: BoxDecoration(
                  color: WColors.primaryColor,
                  borderRadius: BorderRadius.circular(24.px),
                ),
                child: WText(
                  "保存",
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 16.px,
                  ),
                ),
              ),
            )
          ],
        ));
  }

  Container _cardItem(String label, Widget child, {double bottom = 0}) {
    return Container(
      margin: EdgeInsets.only(
          top: 10.px, left: 15.px, right: 15.px, bottom: bottom.px),
      decoration: BoxDecoration(
          color: Colors.white, borderRadius: BorderRadius.circular(10.px)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            height: 48.px,
            alignment: Alignment.centerLeft,
            // padding: EdgeInsets.only(left: 15.px),
            child: Row(
              children: [
                WLine(
                  height: 16.px,
                  width: 4.px,
                  color: WColors.primaryColor,
                  marginRight: 15.px,
                ),
                WText(
                  label,
                  style: TextStyle(
                      fontSize: WDimens.tsLarge,
                      color: WColors.mainTextColor,
                      fontWeight: FontWeight.bold),
                )
              ],
            ),
          ),
          WLine(
            height: 1.px,
          ),
          child
        ],
      ),
    );
  }

  Widget _customerInfo(Leads leadsInfo) {
    return Column(
      children: [
        LabelItem(
          labelType: LabelType.INPUT,
          isMust: true,
          label: "客户名称",
          maxLength: 50,
          onChanged: (text) {
            leadsInfo.customerName = text;
          },
          value: leadsInfo.customerName,
        ),
        LabelItem(
          label: "性别",
          isMust: true,
          labelType: LabelType.LIST,
          onSelected: (value) {
            leadsInfo.sex = value == null ? null : int.parse(value);
          },
          dataList: WConstant.sexList,
          value: leadsInfo.sex.toString(),
        ),
        LabelItem(
          labelType: LabelType.INPUT,
          isMust: true,
          label: "手机号码",
          onChanged: (text) {
            leadsInfo.phone = text;
          },
          value: leadsInfo.phone,
        ),
        LabelItem(
          labelType: LabelType.INPUT,
          label: "微信号",
          maxLength: 30,
          onChanged: (text) {
            leadsInfo.wechat = text;
          },
          value: leadsInfo.wechat,
        ),
        LabelItem(
          label: "客户类型",
          isMust: true,
          labelType: LabelType.LIST,
          onSelected: (value) {
            setState(() {
              leadsInfo.customerType = value == null ? null : int.parse(value);
              if(leadsInfo.customerType == 24281001) {
                leadsInfo.companyName = null;
              }
            });
          },
          dataList: WConstant.customerTypeList,
          value: leadsInfo.customerType.toString(),
        ),
        if (leadsInfo.customerType == 24281002)
          LabelItem(
            labelType: LabelType.INPUT,
            label: "公司名称",
            maxLength: 50,
            onChanged: (text) {
              leadsInfo.companyName = text;
            },
            value: leadsInfo.companyName,
          ),
        LabelItem(
          label: "证件类型",
          labelType: LabelType.DROW_DOWN,
          onSelected: (value) {
            leadsInfo.idType = value == null ? null : int.parse(value);
          },
          dataList: WConstant.cardTypeList,
          value: leadsInfo.idType.toString(),
        ),
        LabelItem(
          labelType: LabelType.INPUT,
          maxLength: 50,
          label: "证件号码",
          onChanged: (text) {
            leadsInfo.idNo = text;
          },
          value: leadsInfo.idNo,
        ),
        LabelItem(
          label: "省市区",
          labelType: LabelType.CITY,
          cityData: cityData,
          onSelected: (res) {
            leadsInfo.province = int.parse(res.provinceId);
            leadsInfo.city = int.parse(res.cityId);
            leadsInfo.county = int.parse(res.areaId);
          },
          value: leadsInfo.county.toString(),
        ),
        LabelItem(
          labelType: LabelType.INPUT,
          maxLength: 50,
          label: "详细地址",
          onChanged: (text) {
            leadsInfo.address = text;
          },
          value: leadsInfo.address,
        ),
        getBirthday(),
        // LabelItem(
        //   labelType: LabelType.DATE,
        //   minDateTime: DateTime(1970, 1, 1),
        //   label: "客户生日",
        //   onDateChanged: (text) {
        //     setState(() {
        //       leadsInfo.birthday = text;
        //     });
        //   },
        //   selectedDate: leadsInfo.birthday,
        // ),
        LabelItem(
          labelType: LabelType.INPUT,
          label: "年龄",
          maxLength: 3,
          onChanged: (text) {
            setState(() {
              leadsInfo.age = text;
            });

          },
          value: leadsInfo.age,
        ),
        LabelItem(
          labelType: LabelType.INPUT,
          label: "电子邮箱",
          maxLength: 50,
          onChanged: (text) {
            leadsInfo.eMail = text;
          },
          value: leadsInfo.eMail,
        ),
        LabelItem(
          labelType: LabelType.INPUT,
          label: "联系人",
          maxLength: 20,
          onChanged: (text) {
            leadsInfo.contactName = text;
          },
          value: leadsInfo.contactName,
        ),
        LabelItem(
          labelType: LabelType.INPUT,
          label: "联系人电话",
          onChanged: (text) {
            leadsInfo.contactPhone = text;
          },
          value: leadsInfo.contactPhone,
        ),
        const LabelItem(
          label: "客户标签",
          value: "",
          isLast: true,
        ),
        Container(
          decoration: BoxDecoration(
              color: Colors.white,
              border: Border(
                bottom: BorderSide(
                  color: WColors.border, // 边框颜色
                  width: 0.5.px, // 边框宽度
                ),
              )),
          child: MultiDropdown<CustomerTag>(
            items: items,
            controller: _controller,
            enabled: true,
            searchEnabled: false,
            chipDecoration: ChipDecoration(
              labelStyle: TextStyle(
                  color: WColors.white,
                  fontSize: WDimens.tsLabel),
              backgroundColor: WColors.primaryColor,
              wrap: true,
              runSpacing: 2,
              spacing: 10,
            ),
            fieldDecoration: FieldDecoration(
              hintText: '请选择',
              hintStyle: TextStyle(
                  color: WColors.hintTextColor,
                  fontSize: WDimens.tsLabel),
              showClearIcon: true,
              border: const OutlineInputBorder(
                  borderSide:
                  BorderSide(width: 0, color: Colors.transparent)),
              focusedBorder: const OutlineInputBorder(
                  borderSide:
                  BorderSide(width: 0, color: Colors.transparent)),
            ),
            dropdownDecoration: const DropdownDecoration(
              marginTop: 0,
              maxHeight: 500,
            ),
            dropdownItemDecoration: DropdownItemDecoration(
              selectedIcon:
              const Icon(Icons.check_box, color: WColors.primaryColor),
              disabledIcon:
              Icon(Icons.lock, color: Colors.grey.shade300),
            ),
            onSelectionChange: (selectedItems) {
              leadsInfo.appCustomerTagList = selectedItems
                  .map((item) => {"tagName": item.tagName, "id": item.id})
                  .toList();
            },
          ),
        ),
      ],
    );
  }

  Widget _otherInfo(Leads leadsInfo) {
    return Column(
      children: [
        if (!isSalesman)
          LabelItem(
            label: "销售顾问",
            isMust: true,
            labelType: LabelType.DROW_DOWN,
            onSelected: (value) {
              setState(() {
                leadsInfo.saleman = value == null ? null : int.parse(value);
                leadsInfo.salemanName = CommonReqUtils.exchangeCodeToName2(
                    WConstant().salesmanList, leadsInfo.saleman);
              });
            },
            dataList: WConstant().salesmanList,
            value: leadsInfo.saleman.toString(),
          ),
        if (isSalesman)
          LabelItem(
            label: "销售顾问",
            isEnabled: false,
            isMust: true,
            value: WConstant().userInfo.employeeName,
          ),
        LabelItem(
          label: "意向级别",
          isMust: true,
          isModel: true,
          listItemWidth: 34.px,
          labelType: LabelType.LIST,
          onSelected: (value) {
            leadsInfo.level = value == null ? null : int.parse(value);
          },
          dataList: WConstant.intentRangeList,
          value: leadsInfo.level.toString(),
        ),
        LabelItem(
          label: "意向车型",
          isMust: true,
          labelType: LabelType.DROW_DOWN,
          onSelected: (value) {
            setState(() {
              leadsInfo.modelId = value;
            });
          },
          dataList: CommonReqUtils.getLabelListByKey(CommonReqUtils.carType),
          value: leadsInfo.modelId.toString(),
        ),
        LabelItem(
          label: "线索来源",
          isMust: true,
          labelType: LabelType.DROW_DOWN,
          onSelected: (value) {
            setState(() {
              setState(() {
                leadsInfo.clueSource = value == null ? null : int.parse(value);
              });
            });
          },
          dataList: WConstant.leaderSourceLst,
          value: leadsInfo.clueSource.toString(),
        ),
        if (leadsInfo.clueSource == 10091002)
          LabelItem(
            label: "市场活动",
            isMust: true,
            labelType: LabelType.DROW_DOWN,
            onSelected: (value) {
              leadsInfo.activityId = value == null ? null : int.parse(value);
            },
            dataList: activityList,
            value: leadsInfo.activityId.toString(),
          ),
        getIntentDate(),
        // LabelItem(
        //   labelType: LabelType.DATE,
        //   label: "意向购车日期",
        //   minDateTime: DateTime.now(),
        //   selectedDate: leadsInfo.purchaseDate,
        //   onDateChanged: (text) {
        //     setState(() {
        //       leadsInfo.purchaseDate = text;
        //     });
        //   },
        // ),
        LabelItem(
          key: isSubstitutionKey2,
          label: "是否置换",
          labelType: LabelType.LIST,
          onSelected: (value) {
            leadsInfo.isSubstitution = value == null ? null : int.parse(value);
          },
          dataList: WConstant.yesOrNoList,
          value: leadsInfo.isSubstitution.toString(),
        ),
        LabelItem(
          key: isLoanKey2,
          label: "是否需要贷款",
          labelType: LabelType.LIST,
          onSelected: (value) {
            leadsInfo.isLoan = value == null ? null : int.parse(value);
          },
          dataList: WConstant.yesOrNoList,
          value: leadsInfo.isLoan.toString(),
        ),
        LabelItem(
          key: budgetKey2,
          labelType: LabelType.INPUT,
          maxLength: 50,
          label: "购车预算",
          onChanged: (text) {
            leadsInfo.budgetAmount = text;
          },
          value: leadsInfo.budgetAmount,
        ),
        LabelItem(
          key: remarkKey2,
          labelType: LabelType.TEXTAREA,
          label: "备注",
          maxTextLength: 1000,
          isLast: true,
          onChanged: (text) {
            leadsInfo.remark = text;
          },
          value: leadsInfo.remark,
        ),
        CommonAttachment(
          key: picKey2,
          onSelected: (values, images) {
            _attachmentImages = images;
            List<Map<String, dynamic>> picList = [];
            if (values.isEmpty) {
              leadsInfo.filesList = null;
            } else {
              for (int i = 0; i < values.length; i++) {
                Map<String, dynamic> fileMap = {
                  "fileUploadInfoId": values[i],
                  "url": null
                };
                picList.add(fileMap);
              }
              leadsInfo.filesList = picList;
            }
          },
        )
      ],
    );
  }

  Widget getIntentDate() {
    return Container(
      height: 45.px,
      padding: EdgeInsets.symmetric(horizontal: 15.px),
      decoration: BoxDecoration(
          color: Colors.white,
          border: Border(
            bottom: BorderSide(
              color: WColors.border, // 边框颜色
              width: 0.5.px, // 边框宽度
            ),
          )),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              WText(
                "意向购车日期",
                style: TextStyle(
                    color: WColors.mainTextColor, fontSize: WDimens.tsLabel),
              ),
            ],
          ),
          GestureDetector(
              onTap: () {
                _showDatePickerForDate(
                    DateTime.now(),
                    null,
                    DateUtil.getDateTime(
                        leadsInfo.purchaseDate ?? ""))
                    .then((dateTime) {
                  if (dateTime != null && dateTime.isNotEmpty) {
                    var selectDate = dateTime[0];
                    var currentDate = DateUtil.formatDate(selectDate,
                        format: DateFormats.y_mo_d);
                    setState(() {
                      leadsInfo.purchaseDate = currentDate;
                    });
                  }
                });
              },
              child: SizedBox(
                height: 48.px,
                width: SizeUtils.screenW() - 150.px,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  mainAxisSize: MainAxisSize.max,
                  children: [
                    Text(
                      (leadsInfo.purchaseDate == null || leadsInfo.purchaseDate == "") ? "请选择" : leadsInfo.purchaseDate.toString(),
                      style: TextStyle(
                        color: (leadsInfo.purchaseDate == null || leadsInfo.purchaseDate == "")
                            ? WColors.CCCCCCC
                            : WColors.subTextColor,
                        fontSize: WDimens.tsLabel,
                      ),
                    ),
                    SizedBox(
                      width: 5.px,
                    ),
                    Image.asset(
                      "images/ic_right.png",
                      color: WColors.CCCCCCC,
                      width: 12.px,
                    ),
                  ],
                ),
              ))
        ],
      ),
    );
  }

  Widget getBirthday() {
    return Container(
      height: 45.px,
      padding: EdgeInsets.symmetric(horizontal: 15.px),
      decoration: BoxDecoration(
          color: Colors.white,
          border: Border(
            bottom: BorderSide(
              color: WColors.border, // 边框颜色
              width: 0.5.px, // 边框宽度
            ),
          )),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              WText(
                "客户生日",
                style: TextStyle(
                    color: WColors.mainTextColor, fontSize: WDimens.tsLabel),
              ),
            ],
          ),
          GestureDetector(
              onTap: () {
                _showDatePickerForDate(
                    DateTime(1970, 1, 1),
                    null,
                    DateUtil.getDateTime(
                        leadsInfo.birthday ?? ""))
                    .then((dateTime) {
                  if (dateTime != null && dateTime.isNotEmpty) {
                    var selectDate = dateTime[0];
                    var currentDate = DateUtil.formatDate(selectDate,
                        format: DateFormats.y_mo_d);
                    setState(() {
                      leadsInfo.birthday = currentDate;
                    });
                  }
                });
              },
              child: SizedBox(
                height: 48.px,
                width: SizeUtils.screenW() - 150.px,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  mainAxisSize: MainAxisSize.max,
                  children: [
                    Text(
                      (leadsInfo.birthday == null || leadsInfo.birthday == "") ? "请选择" : leadsInfo.birthday.toString(),
                      style: TextStyle(
                        color: (leadsInfo.birthday == null || leadsInfo.birthday == "")
                            ? WColors.CCCCCCC
                            : WColors.subTextColor,
                        fontSize: WDimens.tsLabel,
                      ),
                    ),
                    SizedBox(
                      width: 5.px,
                    ),
                    Image.asset(
                      "images/ic_right.png",
                      color: WColors.CCCCCCC,
                      width: 12.px,
                    ),
                  ],
                ),
              ))
        ],
      ),
    );
  }

  Future _showDatePickerForDate(minDateTime, maxDateTime, selectDate) async {
    return CommonDate.showPicker(
        context: context,
        firstDate: minDateTime ?? DateTime(2020, 1, 1),
        lastDate: maxDateTime ?? DateTime(2030, 12, 31),
        currentDate: selectDate,
        value: [selectDate ?? DateTime.now()]);
  }
}
